package com.yx.cloud.activity;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.iot.product.sweeper.bean.Appointment;
import com.iot.product.sweeper.bean.QuietHour;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.config.SweeperProductConfig;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.ChangeAppointmentParam;
import com.iot.sweeper.param.DeleteAppointmentParam;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.Interface.EventForwardingHelper;
import com.yx.cloud.R;
import com.yx.cloud.adapter.AlarmClockAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.FmAlarmClockBinding;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.CommonConfirmDialog2;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.StatusBarColorUtils;
import com.yx.cloud.utils.ToastUtil;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.yx.cloud.view.DefaultHeader;

import java.util.ArrayList;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;


/**
 * 创建时间 : 2017/10/11.
 * 创建人 :
 * 功能描述 : 预约闹钟界面
 */

public class AlarmClockActivity extends BaseActivity implements AlarmClockAdapter.Callback, View.OnClickListener {
    private static final String TAG = "AlarmClockActivity";
    private LoadProgressDialog loadProgressDialog;
    private AlarmClockAdapter alarmdapter;
    private SwipeMenuListView AlarmListView;
    private Dialog dialog;
    private List<Appointment> alarmData;
    private Robot robot;
    private FmAlarmClockBinding binding;

    @Override
    public void onCreate() {
        binding = FmAlarmClockBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initData();
//        initEvent();
    }


    private void initData() {
        //设置状态栏颜色
        StatusBarColorUtils.setStatusBarColor(this, R.color.white, "0");

//        binding.bl.setBounceHandler(new NormalBounceHandler(), binding.lsitViewAlarm);//设置滚动冲突的控制类
//        binding.bl.setEventForwardingHelper(new EventForwardingHelper() {//自定义事件分发处理
//            @Override
//            public boolean notForwarding(float downX, float downY, float moveX, float moveY) {
//                return true;
//            }
//        });
//        binding.bl.setHeaderView(new DefaultHeader(this), binding.flRoot);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空


        robot = AppContext.get().getCurrentDevice();
        alarmData = new ArrayList<>();
        AlarmListView = findViewById(R.id.lsitView_alarm);
        alarmdapter = new AlarmClockAdapter(this, alarmData, this);
        AlarmListView.setAdapter(alarmdapter);

        AppContext.getProductService().getAppointment();

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
                //Color.rgb(r, g, b)
                openItem.setBackground(new ColorDrawable(getResources().getColor(R.color.background_color6)));
                openItem.setWidth(dp2px(90));
                openItem.setTitle(getString(R.string.U_Delete));
                openItem.setTitleSize(18);
                openItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItem);
            }
        };
        AlarmListView.setMenuCreator(creator);
        AlarmListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        deleteAlarmDialog(getString(R.string.MO_Delete_Tip), position);
                        break;
                }
                return false;
            }
        });

        AlarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (alarmData.size() > 0) {
                    Appointment bean = alarmData.get(position);
                    if (bean.isAppointmentExpired() || bean == null) {
                        return;
                    }

                    Gson gson = new Gson();
                    Intent intent = new Intent(AlarmClockActivity.this, AlarmClockNewActivity.class);
                    intent.putExtra("tag", "update");
                    intent.putExtra("appointment", gson.toJson(bean));
                    intent.putExtra("appointmentList", gson.toJson(alarmData));
                    startActivity(intent);
                }
            }
        });
        //显示加载框
        showLoadingDialog();

        binding.ivAlarmReturn.setOnClickListener(this);
        binding.ivAlarmNew.setOnClickListener(this);
    }

//    private void initEvent() {
//        // 设置上拉加载更多
//        binding.bl.setBounceCallBack(new BounceCallBack() {
//            @Override
//            public void startRefresh() {
//                AppContext.getProductService().getAppointment();
//            }
//
//            @Override
//            public void startLoadingMore() {
//                //loadMoreData();
//            }
//        });
//    }

    private void showLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
        loadProgressDialog = new LoadProgressDialog(this, 6);
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
                Log.i(TAG, "动画执行完毕--------------------------------------------- : ");
                ToastUtil.showShort(AlarmClockActivity.this, R.string.U_T_NetworkTimeout);
                if (newAppointmentList == null || newAppointmentList.size() == 0) {
                    //没有预约数据
                    AlarmListView.setVisibility(View.GONE);
                    binding.llNoAppointment.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        loadProgressDialog.show();
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_alarm_return:
                Intent_utils.backIntent(this);
                break;
            case R.id.iv_alarm_new:
                JSONObject productConfig = AppContext.get().getCurrentDevice().getConfig();
                int maxAlarmCount = productConfig.optInt(ProductConfigConstants.maxAlarmCount);
                if (alarmData.size() >= maxAlarmCount) {
                    ToastUtil.show(AlarmClockActivity.this, getString(R.string.MO_T_Schedule_Maximum), Toast.LENGTH_SHORT);
                    return;
                }

                Intent intent = new Intent(AlarmClockActivity.this, AlarmClockNewActivity.class);
                intent.putExtra("tag", "new");
                intent.putExtra("appointmentList", new Gson().toJson(alarmData));
                startActivity(intent);
                break;
        }
    }

    @Override
    public void click(View v, int position, String str, boolean isChecked) {
        if (RomUtils.isFastClick()) {
            return;
        }

        if (v.getId() == R.id.ll_alarmQueryIcon) {
            CommonConfirmDialog2.newBuilder()
                    .context(this)
                    .message(getString(R.string.MO_Schedule_Fail_Tip))
                    .btn2Name(getString(R.string.U_Delete))
                    .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                        @Override
                        public boolean onConfirm() {
                            showLoadingDialog();
                            deleteAlarm(position);
                            return true;
                        }

                        @Override
                        public boolean onCancel() {
                            return true;
                        }
                    }).build().show();
        } else if (v.getId() == R.id.tb_isopen) {
            if (!v.isPressed()) {
                return;
            }
            Appointment appointment = alarmdapter.getItem(position);
            //显示加载框
            showLoadingDialog();
            appointment.setEnable(isChecked);
            appointment.setSwitch(true);
            LogUtils.i("setEnable");
            ChangeAppointmentParam param = ChangeAppointmentParam.newBuilder().appointment(appointment).build();
            AppContext.getProductService().switchAppointment(param);
        }
    }

    private List<Appointment> newAppointmentList;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_QUERY_ALARM:
                if (event.isResult()) {
                    if (loadProgressDialog != null && loadProgressDialog.isShowing()) {
                        loadProgressDialog.dismiss();
                    }
//                    binding.bl.setRefreshCompleted();
                    // bl.setLoadingMoreCompleted();
                    newAppointmentList = (List<Appointment>) event.getContent();
                    LogUtils.i(": 查询到预约列表--------------- : " + new Gson().toJson(newAppointmentList));
                    //有勿扰开启时 显示提示
                    List<QuietHour> quietHourList = robot.getQuietHourList();
                    if (quietHourList.size() > 0 && quietHourList.get(0).isEnable()) {
                        int startTime = quietHourList.get(0).getStartTime();
                        int endTime = quietHourList.get(0).getEndTime();
                        String dataSign;
                        if (startTime >= endTime) {
                            dataSign = getString(R.string.MO_NextDay);
                        } else {
                            dataSign = "";
                        }
                        binding.alarmDisturbRemind.setVisibility(View.VISIBLE);

                        String time = getTimeString(startTime) + "-" + dataSign + getTimeString(endTime);
                        String result = getResources().getString(R.string.U_Dnd_NoSchedule).replace("{X}", time);
                        binding.tvDisturbReminder.setText(result);


                    } else {
                        binding.alarmDisturbRemind.setVisibility(View.GONE);
                    }
                    alarmData.clear();
                    if (newAppointmentList.size() <= 0) {
                        //没有预约数据
                        AlarmListView.setVisibility(View.GONE);
                        binding.llNoAppointment.setVisibility(View.VISIBLE);
                        return;
                    } else {
                        alarmData.clear();
                        alarmData.addAll(newAppointmentList);
                        alarmdapter.notifyDataSetChanged();
                        binding.llNoAppointment.setVisibility(View.GONE);
                        AlarmListView.setVisibility(View.VISIBLE);
                    }
                } else {
                    String content = (String) event.getExtra();
                    LogUtils.i("查询结果 ： " + content);
                    if (content.equals("AJAX_BROWSE_UUID_REPEAT")) {
                        ToastUtil.show(AlarmClockActivity.this, getString(R.string.repeat_operation), Toast.LENGTH_LONG);
                    } else {
                        ToastUtil.show(AlarmClockActivity.this, event.getContent().toString(), Toast.LENGTH_LONG);
                    }

                }
                break;
            case Event.MESSAGE_TYPE_MODIFY_APPOINTMENT:
                if (loadProgressDialog != null && loadProgressDialog.isShowing()) {
                    loadProgressDialog.dismiss();
                }
                if (event.isResult()) {
                    String type = (String) event.getContent();
                    if (type.equals("add") || type.equals("delete") || type.equals("change") || type.equals("switch")) {
                        //添加成功后再次主动调用查询
                        AppContext.getProductService().getAppointment();
                    }
                } else {
                    String extra = (String) event.getExtra();
                    if (extra != null && !extra.equals("")) {
                        String systemLan = LanguageUtils.getProductSuffix(this).toUpperCase();
                        if ("LINKAGE_TIMER_OVER_MAX_LIMIT_30".equals(extra) && systemLan.equals("KO")) {
                            ToastUtil.show(AlarmClockActivity.this, "예약 일정 생성 가능 숫자를 초과하였습니다.", Toast.LENGTH_SHORT);
                        } else {
                            ToastUtil.show(AlarmClockActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                        }
                    } else {
                        ToastUtil.show(AlarmClockActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                    }
                }
                break;
        }
    }

    private String getTimeString(int time) {
        int hour = time / 3600;
        int min = time / 60 % 60;
        String hourString = hour < 10 ? "0" + hour : "" + hour;
        String minString = min < 10 ? "0" + min : "" + min;
        return hourString + ":" + minString;
    }

    /**
     * 删除预约
     *
     * @param dialogTitle
     * @param position
     */
    private void deleteAlarmDialog(String dialogTitle, int position) {
        dialog = new Dialog(AlarmClockActivity.this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtndeleteAlarmConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtndeleteAlarmCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_centered_dialogTitle);
        mTvDialogTitle.setText(dialogTitle);
        mBtndeleteAlarmConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                showLoadingDialog();

                deleteAlarm(position);

                dialog.dismiss();

            }
        });
        mBtndeleteAlarmCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();

            }
        });
        dialog.show();
    }

    private void deleteAlarm(int position) {
        showLoadingDialog();
        //删除后,把剩下的所有预约发送出去
        Appointment appointment = alarmData.get(position);
        if (appointment == null) {
            return;
        }
        DeleteAppointmentParam param = DeleteAppointmentParam.newBuilder().appointment(appointment).build();
        AppContext.getProductService().deleteAppointment(param);
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        AppContext.getProductService().getAppointment();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //为什么加这个onPause 因为当跳转到添加界面快速点击添加时
        // 这个界面如果没有销毁会收到和添加界面一样的回调
        EventBus.getDefault().unregister(this);
    }
}



